package com.m3958.firstgwt.server.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import com.google.inject.Inject;
import com.m3958.firstgwt.server.model.BaseModel;
import com.m3958.firstgwt.server.model.Role;
import com.m3958.firstgwt.server.model.User;
import com.m3958.firstgwt.server.model.WebSite;

public class WebSiteDao  extends BaseDao<WebSite>{
	
	@Inject
	public WebSiteDao(WebSiteChangeStrategy tasks) {
		super(WebSite.class);
		extraStrategyTask = tasks;
	}
	
	public boolean hasFtpPermission(String userName,String websiteId){
		int wsid;
		try {
			wsid = Integer.parseInt(websiteId);
		} catch (NumberFormatException e) {
			return false;
		}
		
		UserDao udao = injector.getInstance(UserDao.class);
		User user = udao.findByLoginNameOrEmailOrMobile(userName);
		if(user == null){
			return false;
		}else{
			boolean issuper = false;
			for(Role r:user.getRoles()){
				if("superman".equals(r.getOrname())){
					issuper = true;
					break;
				}
			}
			
			String qs;
			Query q;
			if(issuper){
				qs = "SELECT DISTINCT(w) FROM WebSite AS w WHERE w.id = :id";
				q = emp.get().createQuery(qs);
				q.setParameter("id", wsid);
			}else{
				qs = "SELECT DISTINCT(w) FROM WebSite AS w,IN(w.objectRoles) AS r WHERE w.id = :wid AND r.orname = 'OWNER' AND r.id IN (SELECT ur.id FROM User AS u,IN(u.roles) AS ur WHERE  u.id = :uid)";
				q = emp.get().createQuery(qs);
				q.setParameter("wid", wsid);
				q.setParameter("uid", user.getId());
			}
			List<WebSite> lws = q.getResultList();
			if(lws.size() == 1)return true;
		}
		return false;
	}
	
	public List<WebSite> getHasFtpPermissions(String userName){
		UserDao udao = injector.getInstance(UserDao.class);
		User user = udao.findByLoginNameOrEmailOrMobile(userName);
		if(user == null){
			return new ArrayList<WebSite>();
		}else{
			boolean issuper = false;
			for(Role r:user.getRoles()){
				if("superman".equals(r.getOrname())){
					issuper = true;
					break;
				}
			}
			
			String qs;
			Query q;
			if(issuper){
				qs = "SELECT DISTINCT(w) FROM WebSite AS w";
				q = emp.get().createQuery(qs);
			}else{
				qs = "SELECT DISTINCT(w) FROM WebSite AS w,IN(w.objectRoles) AS r WHERE r.orname = 'OWNER' AND r.id IN (SELECT ur.id FROM User AS u,IN(u.roles) AS ur WHERE  u.id = :uid)";
				q = emp.get().createQuery(qs);
				q.setParameter("uid", user.getId());
			}
			return q.getResultList();
		}
	}

	@Override
	public Integer smartCustomCount() {
		return null;
	}

	@Override
	public List<BaseModel> smartCustomFetch() {
		return null;
	}

	@Override
	public List<WebSite> smartNamedQueryFetch() {
		return null;
	}

	@Override
	public Integer smartNamedQueryFetchCount() {
		return null;
	}
}
